﻿CREATE proc spMergeFinancialType
AS

MERGE FinancialType AS Target
USING 
(
	SELECT DISTINCT 
		Id
		, AccountLevel1
		, ISNULL(AccountLevel2, AccountLevel1) as AccountLevel2
		, ISNULL(AccountLevel3, ISNULL(AccountLevel2, AccountLevel1)) as AccountLevel3
	FROM FinancialTypeTemp
) AS Source
ON
(
	Target.Id = Source.Id 
)
WHEN MATCHED THEN
	UPDATE SET 
		AccountLevel1 = Source.AccountLevel1
		, AccountLevel2 = Source.AccountLevel2
		, AccountLevel3 = Source.AccountLevel3
WHEN NOT MATCHED BY Target THEN
	INSERT 
	(
		Id
		, AccountLevel1
		, AccountLevel2
		, AccountLevel3
	) 
	Values
	(
		Source.Id
		, Source.AccountLevel1
		, Source.AccountLevel2
		, Source.AccountLevel3
	);